tic
istart=1;
iend=10;

maxnbr = 4.0;
maxdim = 1.0;
I = imread('Cameraman.tif');
[level, em] = graythresh(I);
bw = im2bw(I, level);
%figure,imshow(bw),title('original image');
bwn = randimg(bw, 0.3);
%figure,imshow(bwn),title('noisy image');
labelmat = zeros(256*256,10);

figure,imshow(bwn);pause(1);
img = reshape(bwn, 1, 256*256);
img = double(img);
disp('Finding neighbors ...');
pause(1);
nbrmat = findnbrs(bwn, maxnbr);
disp('Neighbors construction done');
pause(1);


nbrmattmp = nbrmat-1;
nbrmattmp(nbrmattmp ~= -1)=nbrmattmp(nbrmattmp~=-1)+1;
nbrnumsmat = nbrmat - nbrmattmp;
nbrnums = maxnbr-sum(nbrnumsmat,1);
nbrmat = sort((nbrmat-1),1,'descend');
ys = [0 1];

for i=istart:iend
    fprintf(1, 'run loop for %d\n', i);
    pause(1);
    labelmat(:,i) = treebp_matlab(double(prod(size(img))),...
        maxnbr,maxdim,double(ys),double(nbrnums), ...
        double(nbrmat),img,double(i));
end
toc
for i=istart:iend
figure,imshow(mat2gray(reshape(labelmat(:,i),256,256)));
end